package org.dromara.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.mall.domain.MallGoodsSpec;
import org.dromara.mall.domain.MallGoodsSpecVal;
import org.dromara.mall.domain.bo.MallGoodsSpecBo;
import org.dromara.mall.domain.vo.MallGoodsSpecVo;
import org.dromara.mall.mapper.MallGoodsSpecMapper;
import org.dromara.mall.mapper.MallGoodsSpecValMapper;
import org.dromara.mall.service.IMallGoodsSpecService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.beans.beancontext.BeanContext;
import java.util.Collection;
import java.util.List;
import java.util.Map;


/**
 * 商品规格Service业务层处理
 *
 * @author Lion Li
 * @date 2024-05-20
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MallGoodsSpecServiceImpl implements IMallGoodsSpecService {

    private final MallGoodsSpecMapper baseMapper;
    private final MallGoodsSpecValMapper attrMapper;

    /**
     * 查询商品ID查询规格
     */
    @Override
    public MallGoodsSpecVo queryById(Long id) {
        //查询规格列表（主表）
        MallGoodsSpec goodsSpec = baseMapper.selectById(id);
        MallGoodsSpecVo specVo = new MallGoodsSpecVo();
        //设置返回值
        specVo.setId(goodsSpec.getId());
        specVo.setGoodsId(goodsSpec.getGoodsId());
        specVo.setName(goodsSpec.getName());
        //查询规格值列表（子表）
        LambdaQueryWrapper<MallGoodsSpecVal> attrWrapper = new LambdaQueryWrapper<>();
        attrWrapper.eq(MallGoodsSpecVal::getSpecId,id);
        List<MallGoodsSpecVal> attrList = attrMapper.selectList(attrWrapper);
        //把值塞进主表
        specVo.setSpecValues(attrList);
        //返回
        return specVo;
    }
    /*查询分页*/
    @Override
    public TableDataInfo<MallGoodsSpec> queryPageList(MallGoodsSpec bo, PageQuery pageQuery) {
        //查询主表
        Page<MallGoodsSpec> result = baseMapper.queryPageList(pageQuery.build(), bo);
        //遍历主表
        result.getRecords().forEach(x->{
            //查询子表
            LambdaQueryWrapper<MallGoodsSpecVal> attrWrapper = new LambdaQueryWrapper<>();
            //子表关联主表ID
            attrWrapper.eq(MallGoodsSpecVal::getSpecId,x.getId());
            //查询子表内容
            List<MallGoodsSpecVal> specValList = attrMapper.selectList(attrWrapper);
            //把子表数据写入主表
            x.setSpecValues(specValList);
        });
        return TableDataInfo.build(result);

    }
    /**
     * 查询商品规格列表
     */
    @Override
    public List<MallGoodsSpec> queryList(MallGoodsSpec bo) {
        LambdaQueryWrapper<MallGoodsSpec> lqw = buildQueryWrapper(bo);
        return baseMapper.selectList(lqw);
    }

    private LambdaQueryWrapper<MallGoodsSpec> buildQueryWrapper(MallGoodsSpec bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallGoodsSpec> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), MallGoodsSpec::getName, bo.getName());
        return lqw;
    }

    /*TODO 新增商品规格*/
//    @Override
//    public Boolean insertByBo(MallGoodsSpec bo) {
//        //存主表信息
//        validEntityBeforeSave(bo);
//        boolean flag = baseMapper.insert(bo) > 0;
//        //如果主表保存成功
//        if(flag){
//            //主表返回ID
//            bo.setId(bo.getId());
//            //获取并遍历属性值表数据
//            List<MallGoodsSpecVal> specList = bo.getSpecValues();
//            for (MallGoodsSpecVal mallGoodsSpecVal : specList) {
//                //设置子表关联主表的ID
//                mallGoodsSpecVal.setSpecId(bo.getId());
//                //保存子表数据
//                attrMapper.insert(mallGoodsSpecVal);
//            }
//        }
//        return flag;
//    }
    /*根据商品ID保存spec*/
    @Override
    public Boolean insertByBo(MallGoodsSpecBo bo) {
        //存主表信息
        MallGoodsSpec add = MapstructUtils.convert(bo, MallGoodsSpec.class);
        validEntityBeforeSave(add);
        return baseMapper.insert(add) > 0;
    }
    /*自定义根据商品id查询规格列表*/
    @Override
    public List<MallGoodsSpec> selectByGoodsIdList(MallGoodsSpec bo) {
        List<MallGoodsSpec> specs = baseMapper.selectList(new LambdaQueryWrapper<MallGoodsSpec>()
            .eq(MallGoodsSpec::getGoodsId,bo.getGoodsId())
        );
        //查询关联的val表
        for(MallGoodsSpec spec : specs){
            //查询子表
            LambdaQueryWrapper<MallGoodsSpecVal> attrWrapper = new LambdaQueryWrapper<>();
            //子表关联主表ID
            attrWrapper.eq(MallGoodsSpecVal::getSpecId,spec.getId());
            //查询子表内容
            List<MallGoodsSpecVal> specValList = attrMapper.selectList(attrWrapper);
            //把子表数据写入主表
            spec.setSpecValues(specValList);
        }
        return specs;
    }

    /**
     * 修改商品规格
     */
    @Override
    public Boolean updateByBo(MallGoodsSpecBo bo) {
        MallGoodsSpec add = MapstructUtils.convert(bo, MallGoodsSpec.class);
        //修改子表,获取列表数据
        List<MallGoodsSpecVal> specList = bo.getSpecValues();
        //如果子表中有新增数据，则执行新增方法
        specList.forEach(
            a -> {
                //如果有新增数据，就用是否有id做为判断依据
                if (a.getId() == null) {
                    //把父ID塞进来
                    a.setSpecId(bo.getId());
                    //执行新增的方法
                    attrMapper.insert(a);
                }
                //取有ID的值执行编辑的方法
                attrMapper.updateById(a);
            }
        );
        //修改主表
        return baseMapper.updateById(add) > 0;

    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MallGoodsSpec entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商品规格
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        //如果有关联的specValue值，则不能删除
//        for (Long id : ids) {
//            log.info("id是：{}",id);
//            MallGoodsSpecVal val = attrMapper.selectBySpecId(id);
//            if (val != null) {
//                throw new RuntimeException("已被属性关联，无法删除");
//            }
//        }
        //根据规格IDS查询子表
//        List<MallGoodsSpecVal> valIds = attrMapper.selectBySpecIds((List<Long>) ids);
//        if(valIds != null && !valIds.isEmpty()){
//            throw new RuntimeException("已被属性关联，无法删除");
//        }
        LambdaQueryWrapper<MallGoodsSpecVal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MallGoodsSpecVal::getSpecId,ids);
        List<MallGoodsSpecVal> vals = attrMapper.selectList(lqw);
                if(vals != null && !vals.isEmpty()){
            throw new RuntimeException("已被属性关联，无法删除");
        }


        //TODO 删除主表同时删除子表，还没做
        return baseMapper.deleteByIds(ids) > 0;
    }

}
